import configparser
import os
from site import getusersitepackages, getsitepackages
import re
import subprocess
from pathlib import Path
from datetime import datetime


def get_new_version():
    now = datetime.now()
    year = str(now.year)[-2:]  # 获取年份后两位
    month = str(now.month)  # 获取月份

    version_file = Path('YkPywebview/version.py')
    if version_file.exists():
        with open(version_file, 'r') as f:
            content = f.read()
            # 提取当前版本号
            match = re.search(r'__version__ = "(\d+)\.(\d+)\.(\d+)"', content)
            if match:
                old_year, old_month, last_num = match.groups()
                if year != old_year or month != old_month:
                    last_num = 0  # 当年份或月份变化时，重置最后一位
                else:
                    last_num = int(last_num)
            else:
                last_num = 0
    else:
        last_num = 0

    return f"{year}.{month}.{last_num + 1}"


def increment_version():
    new_version = get_new_version()
    version_file = Path('YkPywebview/version.py')
    with open(version_file, 'w') as f:
        f.write(f'__version__ = "{new_version}"\n')
    print(f"版本号已更新为: {new_version}")


def check_build_installed():
    """
    检查build工具是否已安装，如果没有则自动安装
    """
    try:
        subprocess.run(['python', '-m', 'build', '--version'],
                       check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        print("build工具已安装")
        return True
    except (subprocess.CalledProcessError, FileNotFoundError):
        print("build工具未安装，正在自动安装...")
        try:
            subprocess.run(['pip', 'install', 'build'], check=True)
            return True
        except subprocess.CalledProcessError as e:
            print(f"安装build工具失败: {e}")
            return False


def build_package():
    print("正在构建包...")
    if not check_build_installed():
        print("无法构建，因为build工具安装失败")
        return
    subprocess.run(['python', '-m', 'build'], check=True)


def check_twine_installed():
    """
    检查twine是否已安装，如果没有则自动安装
    """
    try:
        subprocess.run(['twine', '--version'], check=True,
                       stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        print("twine已安装")
        return True
    except (subprocess.CalledProcessError, FileNotFoundError):
        print("twine未安装，正在自动安装...")
        try:
            subprocess.run(['pip', 'install', 'twine'], check=True)
            # 安装后再次检查
            try:
                subprocess.run(['twine', '--version'], check=True,
                               stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                return True
            except (subprocess.CalledProcessError, FileNotFoundError):
                if get_twine_path() is None:
                    print("无法找到twine可执行文件，请将twine.exe所在路径设置到环境变量中")
                    return False
                else:
                    return True
        except subprocess.CalledProcessError as e:
            print(f"安装twine失败: {e}")
            return False


def get_twine_path():
    # 优先检查用户目录下的 Scripts
    scripts_dir = os.path.join(os.path.dirname(
        getusersitepackages()), "Scripts")
    twine_path = os.path.join(scripts_dir, "twine.exe")

    # 如果不存在，检查全局 Python 的 Scripts 目录
    if not os.path.exists(twine_path):
        scripts_dir = os.path.join(
            os.path.dirname(getsitepackages()[0]), "Scripts")
        twine_path = os.path.join(scripts_dir, "twine.exe")

    if os.path.exists(twine_path):
        # 将twine目录添加到系统环境变量
        if scripts_dir not in os.environ['PATH']:
            os.environ['PATH'] = scripts_dir + os.pathsep + os.environ['PATH']
        return twine_path
    return None


def upload_package():
    print("正在上传到PyPI...")
    twine_installed = check_twine_installed()
    if not twine_installed:
        print("无法上传，因为twine安装失败")
        return

    # 获取dist目录下最新的whl文件
    whl_files = list(Path('dist').glob('YkPywebview-*.whl'))
    if not whl_files:
        print("错误：未找到dist目录下的whl文件")
        return

    latest_whl = max(whl_files, key=lambda x: x.stat().st_mtime)
    # 从 __token__.toml 加载 token
    token_file = Path('.pypirc')
    if not token_file.exists():
        print("未找到 .pypirc 文件，使用默认上传方式尝试")
        subprocess.run(['twine', 'upload', str(latest_whl)], check=True)

    # 创建 ConfigParser 对象
    config = configparser.ConfigParser()
    # 读取 .pypirc 文件
    config.read(token_file)
    pypi_token = config.get('pypi', 'password', fallback=None)

    if not pypi_token:
        print("未在 .pypirc 中找到有效的 token，使用默认上传方式尝试")
        subprocess.run(['twine', 'upload', str(latest_whl)], check=True)
    else:
        print("使用 token 上传")
        # 执行 twine upload 并传入 token
        subprocess.run([
            'twine', 'upload',
            '--username', '__token__',
            '--password', pypi_token,
            str(latest_whl)
        ], check=True)


def install_package():
    print("正在从本地安装最新版YkPywebview...")
    # 获取dist目录下最新的whl文件
    whl_files = list(Path('dist').glob('YkPywebview-*.whl'))
    if not whl_files:
        print("错误：未找到dist目录下的whl文件")
        return

    latest_whl = max(whl_files, key=lambda x: x.stat().st_mtime)
    subprocess.run(['pip', 'install', str(latest_whl)], check=True)


if __name__ == '__main__':
    increment_version()
    build_package()
    upload_package()
    install_package()
    print("所有操作已完成！")
